package com.root.dreameraadmin.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;

import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.root.dreameraadmin.utils.AsyncGetDataUtil;
import com.root.dreameraadmin.utils.FileCacheUtil;
import com.root.dreameraadmin.utils.HttpConnectionUtil;
import com.root.dreameraadmin.utils.swipemenulistview.SwipeMenu;
import com.root.dreameraadmin.utils.swipemenulistview.SwipeMenuCreator;
import com.root.dreameraadmin.utils.swipemenulistview.SwipeMenuItem;
import com.root.dreameraadmin.utils.swipemenulistview.SwipeMenuListView;

import com.root.dreameraadmin.R;

import org.json.JSONException;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;

import static com.root.dreameraadmin.view.ToolBarView.startIntroAnimation;

public class ListActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,
        SwipeMenuListView.IReflashListener{

    @Nullable
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.toolbar_text)
    TextView toolbar_textView;
    @Bind(R.id.ib_back)
    Button backBtn;
    @Bind(R.id.ib_map)
    Button mapBtn;

    public static final String TAG = "ListActivity";
    SwipeMenuListView list;

    SimpleAdapter listItemAdapter;
    ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
    private int item_id = 0;
    private int position = 0;
    public static int size = 0;
    public static FloatingActionButton fabBtn;
    private ProgressDialog proDia;
    private boolean first = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        ButterKnife.bind(this);

        backBtn.setVisibility(View.GONE);
        mapBtn.setVisibility(View.GONE);

        fabBtn = (FloatingActionButton)findViewById(R.id.fab);

        setSupportActionBar(toolbar);
        startIntroAnimation(toolbar, toolbar_textView, "文物列表");

        new reflashTask().execute();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        if (drawer != null) {
            drawer.setDrawerListener(toggle);
        }
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        if (navigationView != null) {
            navigationView.setNavigationItemSelectedListener(this);
        }

        list = (SwipeMenuListView)findViewById(R.id.listView);
        AsyncGetDataUtil.getJSONData();
        setData();

        list.setOnItemClickListener(itemClickListener);
        fabBtn.setOnClickListener(fabBtnClickListener);
    }


    OnItemClickListener itemClickListener = new OnItemClickListener(){

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            HashMap<String, Object> item = listItem.get(position-1);
            int point_id = (int) item.get("id");
            String name = (String) item.get("name");
            String longitude = (String) item.get("longitude");
            String latitude = (String) item.get("latitude");
            String cross_pictures = (String) item.get("cross_pictures");
            Log.d(TAG,"cross_pictures is"+cross_pictures);

            Intent intent = new Intent();
            intent.setClass(ListActivity.this, PointActivity.class);
            intent.putExtra("point_id", point_id);
            intent.putExtra("name", name);
            intent.putExtra("longitude", longitude);
            intent.putExtra("latitude", latitude);
            intent.putExtra("cross_pictures", cross_pictures);
            ListActivity.this.startActivity(intent);
        }
    };

    DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
            new Thread(){ //new thread to delete
                public void run(){
                    try{
                        HttpConnectionUtil.doDelete(HttpConnectionUtil.PLACEURL+item_id +"/");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if(HttpConnectionUtil.result == "success"){
                                    listItem.remove(position);
                                    listItemAdapter.notifyDataSetChanged();
                                }else{
                                    Toast.makeText(ListActivity.this,"系统维护中,删除无效",Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                    catch(Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    };

    View.OnClickListener fabBtnClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setClass(ListActivity.this, PointAddActivity.class);
            ListActivity.this.startActivity(intent);
        }
    };

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }else{

        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    public void setData(){
        String result = AsyncGetDataUtil.getJSONFromFile();
        try {
            listItem = AsyncGetDataUtil.decodeJsonToPoint(result);

            if(listItem != null) {
                size = listItem.size();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        listItemAdapter = new SimpleAdapter(
                ListActivity.this,
                listItem,//数据源 为填充数据后的ArrayList类型的对象
                R.layout.point_list_item,//子项的布局.xml文件名
                new String[]{"name"},//这个String数组中的元素就是list对象中的列，list中有几这个数组中就要写几列。
                new int[]{R.id.name}//值是对应XML布局文件中的一个ImageView,三个TextView的id
        );
        listItemAdapter.notifyDataSetChanged();
        list.setInterface(this);
        list.setAdapter(listItemAdapter);
        list.setMenuCreator(creator);
        list.setOnMenuItemClickListener(menuItemClickListener);
    }

    SwipeMenuCreator creator = new SwipeMenuCreator() {

        @Override
        public void create(SwipeMenu menu) {

            SwipeMenuItem openItem = new SwipeMenuItem(getApplicationContext()); // create "open" item
            openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9, 0xCE)));
            openItem.setWidth(dp2px(90));
            openItem.setTitle("编辑");
            openItem.setTitleSize(18);
            openItem.setTitleColor(Color.WHITE);
            menu.addMenuItem(openItem);
            // create "delete" item
            SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext());
            deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
            deleteItem.setWidth(dp2px(90));
            deleteItem.setIcon(R.drawable.ic_delete);
            menu.addMenuItem(deleteItem);
        }
    };


    SwipeMenuListView.OnMenuItemClickListener menuItemClickListener
            = new SwipeMenuListView.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(int item_position, SwipeMenu menu, int index) {
            HashMap<String, Object> item = listItem.get(item_position);
            item_id = (int) item.get("id");
            position = item_position;

            switch (index) {
                case 0:
                    int point_id = (int) item.get("id");
                    String name = (String) item.get("name");
                    String longitude = (String) item.get("longitude");
                    String latitude = (String) item.get("latitude");

                    Intent intent = new Intent();
                    intent.setClass(ListActivity.this, PointInfoActivity.class);
                    intent.putExtra("point_id", point_id);
                    intent.putExtra("name", name);
                    intent.putExtra("longitude", longitude);
                    intent.putExtra("latitude", latitude);
                    ListActivity.this.startActivity(intent);
                    break;
                case 1:
                    new AlertDialog.Builder(ListActivity.this)
                            .setMessage("要删除该处文物吗?")
                            .setPositiveButton("删除", positiveListener)
                            .setNegativeButton("取消", new DialogInterface.OnClickListener(){//添加返回按钮
                                @Override
                                public void onClick(DialogInterface dialog, int which) {//响应事件
                                    dialog.dismiss();
                                }
                            }).show();//在按键响应事件中显示此对话框
                    break;
            }

            /**
             * 重新显示右下角button
             */
            if(position +1 == size) {
                fabBtn.setAlpha(1.0f);
                fabBtn.setClickable(true);
            }
            return false;
        }
    };

    @Override
    public void onReflash() {

        new reflashTask().execute();

//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run(){
//                try {
//                    FileCacheUtil.cleanJSONCache();
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//                AsyncGetDataUtil.getDataFromServer();
//
//                // ui
//                new reflashTask().execute();
//                int count = 0;
//                while(!jsonUpdate && count <= 10) {
//                    try {
//                        Thread.sleep(500);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    count++;
//                }
//                setData();
//                list.reflashComplete();

//            }
//        }, 5000);
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    @Override
    protected void onResume(){
        super.onResume();
        fabBtn.setAlpha(1.0f);
        fabBtn.setClickable(true);
    }

    public class reflashTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            if(first){
                first = false;
                proDia = new ProgressDialog(ListActivity.this);
                proDia.setMessage("加载中，请稍候");
                proDia.show();
            }
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                try {
                    FileCacheUtil.cleanJSONCache();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                AsyncGetDataUtil.getDataFromServer();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void integer) {
            if (HttpConnectionUtil.result == "success") {
                Toast.makeText(ListActivity.this, "加载成功!", Toast.LENGTH_SHORT).show();
                setData();
            } else {
                Toast.makeText(ListActivity.this, "加载失败!", Toast.LENGTH_SHORT).show();
            }

            if(proDia != null){
                proDia.dismiss();
            }
            list.reflashComplete();
        }
    }

}